<template>
  <div class="login-container">
    <!-- Logo 区域 -->
    <div class="login-header">
      <div class="logo">
        <img src="../../assets/APP/Logo.png" alt="FunChat" class="logo-image" />
        <h1 class="app-title">XLChat</h1>
      </div>
      <p class="login-subtitle">欢迎使用 XLChat 开始你的聊天之旅</p>
    </div>

    <!-- 登录表单 -->
    <form class="login-form" @submit.prevent="submitForm">
      <!-- 用户名输入 -->
      <div class="form-group">
        <div class="input-wrapper">
          <input
            id="username"
            v-model="loginForm.username"
            type="text"
            class="form-control"
            :class="{
              'is-invalid': v$.username.$error,
              'is-valid': v$.username.$dirty && !v$.username.$invalid
            }"
            placeholder="请输入用户名或邮箱"
            autocomplete="username"
            @input="v$.username.$touch()"
            @blur="v$.username.$touch()"
          />
        </div>
        <div v-if="v$.username.$error" class="form-error">
          {{ v$.username.$errors[0].$message }}
        </div>
      </div>
      <!-- 密码输入 -->
      <div class="form-group">
        <div class="input-wrapper">
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            class="form-control"
            :class="{
              'is-invalid': v$.password.$error,
              'is-valid': v$.password.$dirty && !v$.password.$invalid
            }"
            placeholder="请输入密码"
            autocomplete="current-password"
            @input="v$.password.$touch()"
            @blur="v$.password.$touch()"
          />
        </div>
        <div v-if="v$.password.$error" class="form-error">
          {{ v$.password.$errors[0].$message }}
        </div>
      </div>
      <!-- 忘记密码 -->
      <div class="form-group">
        <div class="remember-forgot-wrapper justify-end">
          <a href="#" class="forgot-password">忘记密码？</a>
        </div>
      </div>
      <!-- 登录按钮 -->
      <button
        type="submit"
        class="login-button"
        :disabled="isLoading || v$.$invalid"
        :class="{
          loading: isLoading,
          disabled: v$.$invalid
        }"
      >
        <span v-if="isLoading" class="loading-spinner"></span>
        {{ isLoading ? '登录中...' : '登录' }}
      </button>

      <!-- 登录错误提示 -->
      <div v-if="loginError" class="login-error">
        {{ loginError }}
      </div>
    </form>

    <!-- 底部链接 -->
    <div class="login-footer">
      <div class="register-link">还没有账号？<a href="#">立即注册</a></div>
      <div class="about-section">
        <button class="about-button" @click="showAbout = true">
          <svg class="about-icon" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
            <path
              d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"
            />
          </svg>
          <span class="about-text">关于应用</span>
        </button>
      </div>
    </div>

    <!-- About 模态框 -->
    <About v-if="showAbout" @close="showAbout = false" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useEventListener } from '@vueuse/core'
import { useUserStore } from '@/store/user'
import { login, type LoginCredentials } from '@/api/auth'
import { sendLoginSuccess } from '@/api/ipc'
import { Toast } from '@/libs/Toast'
import About from './About.vue'
import { useVuelidate } from '@vuelidate/core'
import { required, helpers, minLength } from '@vuelidate/validators'

const router = useRouter()
const userStore = useUserStore()
const showAbout = ref(false)
const loginError = ref('')
const ipcRenderer = window.electron?.ipcRenderer

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 登录状态
const isLoading = ref(false)

// 自定义验证器
const isValidUsername = (value: string): boolean => {
  return /^[\w.-]+@[\w.-]+\.\w+$|^[a-zA-Z0-9_]{3,20}$/.test(value)
}

const containsLetterAndNumber = (value: string): boolean => {
  return /^(?=.*[a-zA-Z])(?=.*\d)/.test(value)
}

// 定义验证规则
const rules = {
  username: {
    required: helpers.withMessage('请输入用户名或邮箱', required),
    validFormat: helpers.withMessage('请输入有效的邮箱或用户名', isValidUsername)
  },
  password: {
    required: helpers.withMessage('请输入密码', required),
    minLength: helpers.withMessage('密码长度不能少于6位', minLength(6)),
    containsLetterAndNumber: helpers.withMessage('密码必须包含字母和数字', containsLetterAndNumber)
  }
}

const v$ = useVuelidate(rules, loginForm, { $autoDirty: true })

// 监听键盘回车事件
useEventListener('keydown', (e: KeyboardEvent) => {
  if (e.key === 'Enter' && !v$.value.$invalid && !isLoading.value) {
    submitForm()
  }
})

// 表单提交处理
const submitForm = async (): Promise<void> => {
  const result = await v$.value.$validate()
  if (!result) return

  await handleLogin()
}

// 登录处理
const handleLogin = async (): Promise<void> => {
  loginError.value = ''
  isLoading.value = true

  try {
    // 准备登录凭证
    const credentials: LoginCredentials = {
      username: loginForm.username,
      password: loginForm.password
    }
    // 调用API服务进行登录
    const userResponse = await login(credentials)
    // 登录成功，存储用户信息到状态管理
    userStore.setUser(userResponse)

    // 显示登录成功提示
    Toast.success('登录成功，正在跳转...')
    if (ipcRenderer) {
      // 使用标准化的IPC服务发送登录成功消息
      sendLoginSuccess({
        username: userResponse.username,
        loginTime: new Date().toISOString(),
        id: userResponse.id,
        token: userResponse.token || ''
      })

      // 路由跳转到home页面
      router.push('/home')
    } else {
      // Web环境：直接使用路由跳转
      console.log('Web环境，直接跳转到主页')
      router.push('/home')
    }
  } catch (error: unknown) {
    const errorMsg = error instanceof Error ? error.message : '登录失败，请检查用户名和密码'
    console.error('登录失败:', error)

    // 使用 Toast 显示错误信息
    Toast.error(errorMsg, {
      title: '登录失败',
      duration: 4000
    })

    // 保留错误信息用于表单内显示
    loginError.value = errorMsg
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background: var(--background-color-secondary);
  padding: var(--spacing-large);
  text-align: center;
  box-sizing: border-box;
  overflow: hidden;
  -webkit-app-region: drag;
}

.login-header {
  text-align: center;
  margin-bottom: var(--spacing-xxlarge);
}

.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: var(--spacing-medium);
}

.logo-image {
  width: 64px;
  height: 64px;
  margin-bottom: var(--spacing-small);
}

.app-title {
  font-size: var(--font-size-xxlarge);
  font-weight: var(--font-weight-semibold);
  color: var(--text-color-primary);
  margin: 0;
}

.login-subtitle {
  color: var(--text-color-secondary);
  font-size: var(--font-size-base);
  margin: 0;
}

.login-form {
  margin-bottom: var(--spacing-large);
}

.form-group {
  margin-bottom: var(--spacing-medium);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-mini);
  font-weight: var(--font-weight-medium);
  color: var(--text-color-secondary);
  font-size: var(--font-size-small);
}

.input-wrapper {
  position: relative;
}

.form-control {
  width: 100%;
  height: 44px;
  padding: var(--spacing-base) var(--spacing-medium);
  border: 1px solid var(--border-color-normal);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  transition: all var(--transition-duration) var(--transition-timing-function);
  background-color: var(--background-color-primary);
  -webkit-app-region: no-drag;
}

/* 移除密码切换相关样式 */

.form-control:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(51, 112, 255, 0.1);
}

.form-control.is-invalid {
  border-color: var(--error-color);
}

.form-control.is-valid {
  border-color: #28a745;
  box-shadow: 0 0 0 2px rgba(40, 167, 69, 0.1);
}

.form-control::placeholder {
  color: var(--text-color-tertiary);
}

/* 清理未使用的样式 */

/* 密码切换功能已移除 */

.form-error {
  margin-top: var(--spacing-mini);
  font-size: var(--font-size-small);
  color: var(--error-color);
}

.login-error {
  margin-top: var(--spacing-medium);
  font-size: var(--font-size-small);
  color: var(--error-color);
  text-align: center;
  padding: var(--spacing-small);
  background-color: rgba(220, 53, 69, 0.1);
  border-radius: var(--border-radius-small);
}

.login-button {
  width: 100%;
  height: 44px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: all var(--transition-duration) var(--transition-timing-function);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-small);
  -webkit-app-region: no-drag;
}

.login-button:hover:not(:disabled) {
  background-color: var(--primary-color-hover);
  transform: translateY(-1px);
  box-shadow: var(--shadow-medium);
}

.login-button:active:not(:disabled) {
  background-color: var(--primary-color-active);
  transform: translateY(0);
}

.login-button:disabled,
.login-button.disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.login-button.disabled {
  background-color: var(--border-color-normal);
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.login-footer {
  text-align: center;
}

.remember-forgot-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  width: 100%;
}

.justify-end {
  justify-content: flex-end;
}

.forgot-password {
  display: inline-block;
  color: var(--primary-color);
  text-decoration: none;
  font-size: var(--font-size-small);
  transition: color var(--transition-duration) var(--transition-timing-function);
  -webkit-app-region: no-drag;
  flex-shrink: 0;
}

.forgot-password:hover {
  color: var(--primary-color-hover);
  text-decoration: underline;
}

.register-link {
  font-size: var(--font-size-small);
  color: var(--text-color-secondary);
}

.register-link a {
  color: var(--primary-color);
  text-decoration: none;
  font-weight: var(--font-weight-medium);
  transition: color var(--transition-duration) var(--transition-timing-function);
  -webkit-app-region: no-drag;
}

.register-link a:hover {
  color: var(--primary-color-hover);
  text-decoration: underline;
}

.about-section {
  margin-top: var(--spacing-medium);
}

.about-button {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: rgba(1, 1, 1, 0.4);
  padding: 8px 16px;
  border-radius: 6px;
  font-size: var(--font-size-small);
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  -webkit-app-region: no-drag;
}

.about-icon {
  flex-shrink: 0;
  opacity: 0.8;
  transition: opacity 0.3s ease;
}

.about-button:hover .about-icon {
  opacity: 1;
}

.about-text {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: var(--spacing-small);
  }

  .login-card {
    padding: var(--spacing-large);
  }
}
</style>
